package com.yy.tech.data.helper;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import com.yy.tech.data.context.SecretContent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public interface ObjectMapperInitializer {

    void initialize(ObjectMapper mapper);

    @Component
    @Order(5)
    class DateFormatObjectMapperInitializer implements ObjectMapperInitializer{

        @Autowired
        private Environment env;
        @Override
        public void initialize(ObjectMapper mapper) {
            String dateTimeFormat = env.getProperty(SecretContent.KEY_JACKSON_DATE_FORMAT, SecretContent.DATE_FORMAT);
            String localDateFormat = env.getProperty(SecretContent.KEY_JACKSON_LOCAL_DATE_FORMAT, SecretContent.LOCAL_DATE_FORMAT);
            String localTimeFormat = env.getProperty(SecretContent.KEY_JACKSON_LOCAL_TIME_FORMAT, SecretContent.LOCAL_TIME_FORMAT);
            mapper.setDateFormat(new SimpleDateFormat(dateTimeFormat));
            JavaTimeModule javaTimeModule = new JavaTimeModule();
            javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(dateTimeFormat)));
            javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(localDateFormat)));
            javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(localTimeFormat)));
            javaTimeModule.addDeserializer(LocalDateTime.class,new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(dateTimeFormat)));
            javaTimeModule.addDeserializer(LocalDate.class,new LocalDateDeserializer(DateTimeFormatter.ofPattern(localDateFormat)));
            javaTimeModule.addDeserializer(LocalTime.class,new LocalTimeDeserializer(DateTimeFormatter.ofPattern(localTimeFormat)));
            mapper.registerModule(javaTimeModule);
        }
    }
}
